package com.example.month11.festivalsms.biz;

import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.telephony.SmsManager;

import com.example.month11.festivalsms.bean.SendedMsg;
import com.example.month11.festivalsms.db.SmsProvider;

import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

/**
 * 短信发送类
 */
public class SmsBiz {
    private Context mContext;

    public SmsBiz(Context context) {
        this.mContext = context;
    }

    // 短信分割成多条发送，返回值是条数
    public int sendMsg(String number, String msg,
                       PendingIntent sentPi, PendingIntent deliverPi) {
        SmsManager smsManager = SmsManager.getDefault();
        ArrayList<String> contents = smsManager.divideMessage(msg);

        for (String content : contents) {
            smsManager.sendTextMessage(number, null, content, sentPi, deliverPi);
        }
        return contents.size();
    }

    public int sendMsg(Set<String> numbers, SendedMsg msg,
                       PendingIntent sentPi, PendingIntent deliverPi) {
        save(msg); // 保存短信内容到数据库
        int result = 0;
        for (String number : numbers) {
            int count = sendMsg(number, msg.getMsg(), sentPi, deliverPi);
            result += count;
        }
        return result;
    }

    // 保存数据到数据库
    private void save(SendedMsg sendedMsg) {
        sendedMsg.setDate(new Date()); // 当前的日期
        ContentValues values = new ContentValues();
        // 格式转换。Date转long类型.
        values.put(SendedMsg.COLUMN_DATE, sendedMsg.getDate().getTime());
        values.put(SendedMsg.COLUMN_FESTIVAL_NAME, sendedMsg.getFestivalName());
        values.put(SendedMsg.COLUMN_MSG, sendedMsg.getMsg());
        values.put(SendedMsg.COLUMN_NAMES, sendedMsg.getNames());
        values.put(SendedMsg.COLUMN_NUMBERS, sendedMsg.getNumbers());

        mContext.getContentResolver().insert(SmsProvider.URI_SMS_ALL, values);
    }

}
